/**
 * 
 */
package com.ykdl.member.kid.gears;

import java.io.Serializable;
import java.security.InvalidParameterException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.ykdl.member.KidApp;
import com.ykdl.member.base.GlobalContext;
import com.ykdl.member.base.QLog;
import com.ykdl.member.base.interfacedef.IProgress;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.advert.AdverltWebView;
import com.ykdl.member.kid.circle.CircleTopicActivity;
import com.ykdl.member.kid.circle.TopicAndResultActivity;
import com.ykdl.member.kid.doctor.AskDoctorActivity;
import com.ykdl.member.kid.doctor.DoctorInfoActivity;
import com.ykdl.member.kid.doctor.DoctorOnlineActivity;
import com.ykdl.member.kid.doctor.ToAskDoctorActivity;
import com.ykdl.member.kid.regandlogin.RegAndLoginActivity;
import com.ykdl.member.kid.util.ActiveStateUtil;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.member.kid.widget.dialog.DialogImpl;

/**
 * @author yuangg
 * @date Feb 20, 2012
 * @time 2:47:11 PM 正常页面，不适用fragment的基类，封装了退出，action跳转，登录检查的功能
 */
public abstract class BaseScreen extends Activity implements IProgress {
	protected boolean haspoptile = false;// 是否有弹出的排序内容
	public final String TAG = this.getClass().getSimpleName();
	protected Context mContext;
	protected TextView mTitle, remind;
	protected ImageView show_face;
	protected Button mLeft, mRight;
	public static long lastactive = 0;

	/**
	 * action 处理 add 之类的 动作，来自动跳转页面的， pagram 来放置，跳转到指定的tab， tag 来处理是否识别 这个动作
	 */

	public static Hashtable<String, Class<?>> action;
	protected FrameLayout mHolder;
	private LayoutInflater mLayoutInflater;
	public RelativeLayout set_downbut;
	private ProgressDialog mProgressDialog;
	/**
	 * 
	 */
	private ListView poptitle;
	private KidApp mApplication;
	public ProgressDialog progress;
	public DialogImpl dialog;

	public void showProgress(Activity activity) {
		dialog = new DialogImpl();
		progress = (ProgressDialog) dialog.showProgressDialog(this, "正在加载中...",
				new onChannelListener(activity));
	}

	public void dismissProgress() {
		dialog.dismissProgress(progress);
	}

	private class onChannelListener implements DialogInterface.OnCancelListener {
		Activity context;

		public onChannelListener(Activity context) {
			this.context = context;
		}

		@Override
		public void onCancel(DialogInterface dialog) {
			if (context instanceof HomeActivity) {
				context.onKeyDown(KeyEvent.KEYCODE_BACK, null);
			} else {
				context.finish();
			}
		}

	}

	/**
	 * 监听退出的广播，收到之后，finish掉自己
	 */
	private BroadcastReceiver mReceiver2Exit = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			QLog.debug("BaseActivity of " + BaseScreen.this.getClass()
					+ " is finished by Broadcast");
			BaseScreen.this.finish();
		}
	};

	@Override
	public void onConfigurationChanged(Configuration config) {
		try {
			super.onConfigurationChanged(config);
			if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // 横屏时要处理的代码，
																												// //这里的代码是当屏幕横屏时当成竖屏显示
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { // 竖屏时要处理的代码
																													// s
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			}
		} catch (Exception ex) {
		}
	}

	// private BroadcastReceiver[] mReceivers = new BroadcastReceiver[] {
	// mReceiver2Exit, mReceiver2SetupNetwork };

	/** Called when the activity is first created. */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		KidApp.getInstance().getAppManager().addActivity(this);
		setContentView(R.layout.nav_content);
		mContext = this.getApplicationContext();
		mLeft = (Button) findViewById(R.id.left);
		mRight = (Button) findViewById(R.id.right);
		mTitle = (TextView) findViewById(R.id.title);
		remind = (TextView) findViewById(R.id.remind);
		set_downbut = (RelativeLayout) findViewById(R.id.set_downbut);
		mTitle.requestFocus();
		show_face = (ImageView) findViewById(R.id.show_face);
		poptitle = (ListView) findViewById(R.id.poptitle);

		mHolder = (FrameLayout) findViewById(R.id.holder);
		mLayoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		GlobalContext.init(this);
		mApplication = (KidApp) this.getApplication();
		registerReceiver(mReceiver2Exit, new IntentFilter(KidAction.EXIT));
		if (action == null) {

			intitAction();
		}
	}

	/**
	 * 设置内容区的背景图片，默认没有背景，
	 * 
	 * @param resid
	 */
	public void setBackGroud(int resid) {
		mHolder.setBackgroundResource(resid);
	}

	/**
	 * 设置内容区的背景色，默认没有背景，
	 * 
	 * @param resid
	 */
	public void setBackGroudColor(int clor) {
		mHolder.setBackgroundDrawable(null);
		mHolder.setBackgroundColor(clor);
	}

	/**
	 * 设置title的排序 item
	 * 
	 * @param resid
	 */
	public void setTitleItems(String item[], String ids[], int sel) {
		mTitle.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (haspoptile) {
					if (poptitle.getVisibility() == View.GONE) {
						poptitle.setVisibility(View.VISIBLE);
						// mTitle.setCompoundDrawables(null, null,
						// getResources().getDrawable(R.drawable.title_uparrow),
						// null);
						mTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
								R.drawable.title_uparrow, 0);
					} else {
						poptitle.setVisibility(View.GONE);
						// mTitle.setCompoundDrawables(null, null,
						// getResources().getDrawable(R.drawable.title_uparrow),
						// null);
						mTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
								R.drawable.title_downarrow, 0);
					}
				}

			}
		});

		mTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
				R.drawable.title_downarrow, 0);
		// mTitle.setCompoundDrawables(null, null,
		// getResources().getDrawable(R.drawable.title_downarrow), null);
		haspoptile = true;
		poptitle.setAdapter(new TitleAdaper(item, ids));
		poptitle.setSelection(sel);
		poptitle.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				mTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
						R.drawable.title_downarrow, 0);
				processSortItemClick(id);
				// poptitle.setVisibility(View.GONE);
			}
		});
	}

	/**
	 * 设置title的排序 item
	 * 
	 * add 自己的排序处理，id 排序的方式的id
	 * 
	 * @param resid
	 */
	protected void processSortItemClick(long id) {
		// TODO Auto-generated method stub

	}

	class TitleAdaper extends BaseAdapter {

		private String[] tip;
		private String[] ids;
		LayoutInflater lay;

		TitleAdaper(String ptip[], String[] pids) {
			tip = ptip;
			ids = pids;
			lay = LayoutInflater.from(mContext);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return tip.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return Long.parseLong(ids[position]);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = lay.inflate(R.layout.poptitle_item, null);
			TextView tv = (TextView) v.findViewById(R.id.poptip_item);
			tv.setText(tip[position]);
			if (poptitle.getSelectedItemPosition() == position) {
				poptitle.setBackgroundResource(R.drawable.title_popsel);
			}
			return v;
		}

	}

	// public final void setMenuItems(int[] labels, int[] icons,
	// OnClickListener[] clicks) {
	// if (labels == null || icons == null || clicks == null) {
	// throw new InvalidParameterException(
	// "Labels, icons, clicks can't be NULL!");
	// } else if (labels.length != icons.length
	// || icons.length != clicks.length) {
	// throw new InvalidParameterException(
	// "Labels, icons, clicks arries' size MUST be equal!");
	// } else {
	// int len = labels.length;
	// for (int i = 0; i < len; i++) {
	// mButtons[i].setText(labels[i]);
	// mButtons[i].setBackgroundResource(icons[i]);
	// mButtons[i].setOnClickListener(clicks[i]);
	// }
	// for (int j = len; j < mButtons.length; j++) {
	// mButtons[j].setVisibility(View.GONE);
	// }
	// mSetupMenuItems = true;
	// }
	// }

	public final void setTopNav(int title, int left, OnClickListener onLeft,
			int right, OnClickListener onRight) {
		mTitle.setText(title);
		if (onLeft != null) {
			mLeft.setText(left);
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);

		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			mRight.setText(right);
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 
	 * @param title
	 *            标题
	 * @param left
	 *            左边按钮上面的字
	 * @param leftPic
	 *            左边按钮的背景图片，没有设为0
	 * @param onLeft
	 *            左边按钮的点击事件，没有设为null
	 * @param right
	 *            右边按钮上面的字
	 * @param rightPic
	 *            右边按钮的背景图片，没有设为0
	 * @param onRight
	 *            右边按钮的点击事件，没有设为null
	 * @param titlePic
	 *            整个标题的背景图片，没有设为0
	 */
	// 设置各个Activity的title
	public final void setTopTitle(int title, int left, int leftPic,
			OnClickListener onLeft, int right, int rightPic,
			OnClickListener onRight, int titlePic) {
		if (titlePic != 0) {
			set_downbut.setBackgroundResource(titlePic);
		}

		mTitle.setText(title);
		if (onLeft != null) {
			if (left != 0) {
				mLeft.setText(left);
			} else {
				mLeft.setText("");
			}
			if (leftPic != 0) {
				mLeft.setBackgroundResource(leftPic);
			}
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);
		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			if (right != 0) {
				mRight.setText(right);
			} else {
				mRight.setText(null);
			}
			if (rightPic != 0) {
				mRight.setBackgroundResource(rightPic);
			}
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}
	}

	public final void setTopTitle(String title, int left, int leftPic,
			OnClickListener onLeft, int right, int rightPic,
			OnClickListener onRight, int titlePic) {
		if (titlePic != 0) {
			set_downbut.setBackgroundResource(titlePic);
		}

		mTitle.setText(title);
		if (onLeft != null) {
			if (left != 0) {
				mLeft.setText(left);
			} else {
				mLeft.setText("");
			}
			if (leftPic != 0) {
				mLeft.setBackgroundResource(leftPic);
			}
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);
		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			if (right != 0) {
				mRight.setText(right);
			} else {
				mRight.setText(null);
			}
			if (rightPic != 0) {
				mRight.setBackgroundResource(rightPic);
			}
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}
	}

	public final void setTopTitle(String title, int left, int leftPic,
			OnClickListener onLeft, int right, int rightPic,
			OnClickListener onRight, int titlePic, boolean type) {
		if (titlePic != 0) {
			set_downbut.setBackgroundResource(titlePic);
		}

		mTitle.setText(title);
		if (onLeft != null) {
			if (left != 0) {
				mLeft.setText(left);
			} else {
				mLeft.setText("");
			}
			if (leftPic != 0) {
				mLeft.setBackgroundResource(leftPic);
			}
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);
		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			if (right != 0) {
				mRight.setText(right);
			} else {
				mRight.setText(null);
			}
			if (rightPic != 0) {
				mRight.setBackgroundResource(rightPic);
			}
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}

		if (type) {
			remind.setVisibility(View.VISIBLE);
		}
	}

	private boolean checkHomeOrAdd(int left) {
		// String text=getResources().getString(left);
		// if(text.indexOf("首页")!=-1){
		// mLeft.setBackgroundResource(R.drawable.sna_home);
		// mLeft.setText("");
		// return true;
		// }else if(text.indexOf("添加")!=-1){
		// mLeft.setBackgroundResource(R.drawable.diary_add);
		// mLeft.setText("");
		// return true;
		// }
		return false;
	}

	public final void setTopNav(String title, int left, OnClickListener onLeft,
			int right, OnClickListener onRight) {
		mTitle.setText(title);
		if (onLeft != null) {
			mLeft.setText(left);
			mLeft.setOnClickListener(onLeft);
			mLeft.setVisibility(View.VISIBLE);
		} else {
			mLeft.setVisibility(View.INVISIBLE);
		}
		if (onRight != null) {
			mRight.setText(right);
			mRight.setOnClickListener(onRight);
			mRight.setVisibility(View.VISIBLE);
		} else {
			mRight.setVisibility(View.INVISIBLE);
		}
	}

	public final void setTopNav(int title, int left, OnClickListener onLeft,
			int right, OnClickListener onRight, int style) {
		setTopNav(title, left, onLeft, right, onRight);
		if (checkHomeOrAdd(left)) {

		} else if (style == 0) {
			// mLeft.setBackgroundDrawable(getResources().getDrawable(R.drawable.left_button_bg));
			mLeft.setText(" " + mLeft.getText());
		}
		if (onRight != null) {
			checkList(right);
		}
	}

	private void checkList(int right) {
		// String text=getResources().getString(right);
		// if(mRight.getVisibility()==View.VISIBLE&&text.indexOf("列表")!=-1){
		// mRight.setBackgroundResource(R.drawable.sna_pillar);
		// mRight.setText("");
		// }

	}

	public final void setTopNav(String title, int left, OnClickListener onLeft,
			int right, OnClickListener onRight, int style) {
		setTopNav(title, left, onLeft, right, onRight);
		if (style == 0) {
			mLeft.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.left_button_bg));
			mLeft.setText(" " + mLeft.getText());
		}
	}

	public final void setTopNav(String title) {
		mTitle.setText(title);
	}

	public final void setRightNav(String title) {
		mRight.setText(title);
	}

	// public final void checkTab(int check) {
	// mButtons[check].setChecked(true);
	// }

	public void setContent(int layout) {
		mHolder.removeAllViews();
		// mHolder.addView(group);
		// GlobalContext.inflateLayout(layout, mHolder);
		mLayoutInflater.inflate(layout, mHolder);
		// mHolder.setBackgroundResource(R.drawable.coment_back);

	}

	public View getMainParent() {
		View view = (View) mHolder.getParent().getParent();
		return view;
	}

	public void setContent(View view) {
		mHolder.removeAllViews();
		mHolder.addView(view);

	}

	public final void showProgress() {
		// runOnUiThread(new Runnable() {
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		QLog.debug(TAG, "showProgress=================");
		if (mProgressDialog == null && this.getWindow() != null
				&& (!this.isFinishing())) {
			QLog.debug(TAG, "showProgress=================22222222");
			mProgressDialog = ProgressDialog.show(
					BaseScreen.this,
					"",
					ResoureUtil.getResoure().getString(
							R.string.progres_dialog_loading), true, false);
		} else {
			if (this.getWindow() != null && (!this.isFinishing())) {
				QLog.debug(TAG, "showProgress=================333333");
				mProgressDialog.show();
			}
		}
		// }
		// });
	}

	public final void showProgress(String tip) {
		if (mProgressDialog == null && this.getWindow() != null) {
			mProgressDialog = ProgressDialog.show(BaseScreen.this, "", tip,
					true, false);
		} else {
			if (this.getWindow() != null) {
				mProgressDialog.setMessage(tip);
				mProgressDialog.show();
			}
		}
	}

	public final void finishProgress() {

		if (mProgressDialog != null) {
			mProgressDialog.hide();
		}
	}

	/**
	 * Called when the activity is being / now again displayed to the user.
	 */
	@Override
	protected void onStart() {
		super.onStart();
		// checkTab(2);
		// if (!mSetupMenuItems) {
		// throw new InvalidParameterException(
		// "Pls setup bottom menu-items via setMenuItems() in onCreate()");
		// }
	}

	// protected final void upload(String file) {
	// // String uri = GlobalContext.PROJECT_SERVER + KidConfig.PATH_UPLOAD
	// // + getClass().getName();
	// // String uri = "﻿http://192.168.123.26:8080/lmyr" +
	// KidConfig.PATH_UPLOAD
	// // + getClass().getSimpleName().toLowerCase();
	// String uri = "http://192.168.123.26:8080/lmyr/rest/files/update/wth";
	// // String uri = "http://baidu.com";
	// String id = GlobalContext.getDeviceID();
	// String now = String.valueOf(System.currentTimeMillis());
	// String md5 = SecureConnUtils.encode(id, now);
	// // // QLog.debug("suck");
	// // HttpPost req = new HttpPost(Uri.encode(uri));
	// // // QLog.debug("my dick");
	// // // QLog.debug(req.toString());
	// // req.setHeaders(new BasicHeader[] {
	// // new BasicHeader("content-type", "application/json"),
	// // new BasicHeader("deviceId", id), new BasicHeader("date", now),
	// // new BasicHeader("md5", md5), });
	// // // req.setHeader("content-type", "application/json");
	// // // ArrayList shit = new ArrayList();
	// // // shit.add(new BasicNameValuePair("deviceId", id));
	// // // shit.add(new BasicNameValuePair("date", now));
	// // // shit.add(new BasicNameValuePair("md5", md5));
	// // try {
	// // File f = new File(file);
	// // if (f != null) {
	// // byte[] bs = new byte[(int) f.length()];
	// // new BufferedInputStream(new FileInputStream(f)).read(bs);
	// // String log = new String(bs);
	// // QLog.debug(log);
	// // // req.setEntity(new StringEntity(log));
	// // HttpResponse resp = new DefaultHttpClient().execute(req);
	// // // QLog.debug(resp.toString());
	// // QLog.debug("" + resp.getStatusLine());
	// // }
	// // } catch (FileNotFoundException e) {
	// // // TODO Auto-generated catch block
	// // e.printStackTrace();
	// // } catch (IOException e) {
	// // // TODO Auto-generated catch block
	// // e.printStackTrace();
	// // }
	// // // req.set
	// try {
	// URL url = new URL(uri);
	// if (url != null) {
	// HttpURLConnection uc = (HttpURLConnection) url.openConnection();
	// if (uc != null) {
	// uc.setDoOutput(true);
	// uc.setRequestProperty("deviceId", id);
	// uc.setRequestProperty("date", now);
	// uc.setRequestProperty("md5", md5);
	// File f = new File(file);
	// if (f != null) {
	// byte[] bs = new byte[(int) f.length()];
	// new BufferedInputStream(new FileInputStream(f))
	// .read(bs);
	// // String log = new String(bs);
	// // QLog.debug(log);
	// OutputStream os = uc.getOutputStream();
	// if (os != null) {
	// os.write(bs);
	// QLog.debug(uc.getResponseMessage() + '\t'
	// + uc.getResponseCode());
	// }
	// }
	// }
	// }
	// } catch (MalformedURLException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }

	// protected final String download(String file) {
	// String uri = "http://192.168.123.26:8080/lmyr/rest/files/down/wth";
	// HttpUriRequest req = new HttpGet(uri);
	// String id = GlobalContext.getDeviceID();
	// String now = String.valueOf(System.currentTimeMillis());
	// String md5 = SecureConnUtils.encode(id, now);
	// req.setHeaders(new BasicHeader[] {
	// new BasicHeader("content-type", "application/json"),
	// new BasicHeader("deviceId", id), new BasicHeader("date", now),
	// new BasicHeader("md5", md5), });
	// HttpResponse resp;
	// try {
	// resp = new DefaultHttpClient().execute(req);
	// return EntityUtils.toString(resp.getEntity(), "utf-8");
	// } catch (ClientProtocolException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// return "";
	// }

	/** Called when the activity will start interacting with the user. */
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("SplashScreen");
		MobclickAgent.onResume(this);
		if (lastactive != 0) {
			if (System.currentTimeMillis() - lastactive > 1000 * 60 * 60 * 24) {
				QLog.debug(this.getLocalClassName(), "too long not used.....");
				// goAndFinish(HomeActivity.class, 20);
			}
		}
		lastactive = System.currentTimeMillis();
	}

	/**
	 * Called when the system is about to start resuming a previous activity.
	 */
	@Override
	protected void onPause() {
		// GlobalContext.finishProgress();
		MobclickAgent.onPageEnd("SplashScreen");
		MobclickAgent.onPause(this);
		finishProgress();
		super.onPause();
	}

	// /** Called when the activity is no longer visible to the user. */
	// @Override
	// protected void onStop() {
	// // cancelProgress();
	// super.onStop();
	// }

	/** The final call you receive before your activity is destroyed. */
	@Override
	protected void onDestroy() {
		unregisterReceiver(mReceiver2Exit);
		// for (BroadcastReceiver r : mReceivers) {
		// unregisterReceiver(r);
		// }
		QLog.debug("BaseActivity.super.onDestroy()");
		if (mProgressDialog != null)
			mProgressDialog.dismiss();
		super.onDestroy();
	}

	/**
	 * 用来启动单例activity。如果目标activity已经启动，并且用intent传递更新界面的数据，需要在
	 * {@link #onNewIntent}实现相应方法。此时此处的intent不会调用{@link #onCreate}。
	 * */
	@Override
	public void startActivity(Intent intent) {
		// QLog.debug("BaseActivity.startActivity()");
		// intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		super.startActivity(intent);
	}

	protected void startService(Class<?> to) {
		startService(new Intent(this, to));
	}

	/**
	 * 设置 出错的提示
	 * 
	 * @param err
	 *            err,错误提示，
	 * @param tip
	 *            tip 应该操作
	 */
	protected void showErrorTip(String err, String tip) {
		findViewById(R.id.errtip_div).setVisibility(View.VISIBLE);
		((TextView) findViewById(R.id.tv_error_text)).setText(err);
		((TextView) findViewById(R.id.tv_error_text2)).setText(tip);
	}

	/**
	 * 隐藏 出错的提示
	 */
	protected void hidErrorTip() {
		findViewById(R.id.errtip_div).setVisibility(View.GONE);
	}

	/**
	 * 启动其它单例activity。
	 * 
	 * @param Class
	 *            <?> to 要启动的单例activity对应的class。
	 */
	public void go(Class<?> to) {
		Intent o = new Intent(this, to);
		if (o.getComponent().getClassName().indexOf("IaskMainActivity") != -1) {
			sendBroadcast(new Intent(KidAction.EXIT));
		}
		startActivity(o);
	}

	public void go(Class<?> to, String key, Serializable value) {
		startActivity(new Intent(this, to).putExtra(key, value));
	}

	/**
	 * 启动其它单例activity。
	 * 
	 * @param to
	 *            要启动的单例activity对应的class。
	 * @param uri
	 *            必须是绝对路径。
	 * 
	 * @throws InvalidParameterException
	 */
	public final void go(Class<?> to, String uri) {
		check(uri);
		startActivity(new Intent(this, to).setData(Uri.parse(uri)));
	}

	/**
	 * 启动其它单例activity。
	 * 
	 * @param to
	 *            要启动的单例activity对应的class。
	 * @param uri
	 *            必须是绝对路径。
	 * 
	 * @throws InvalidParameterException
	 */
	public void go(Class<?> to, String uri, Bundle extras) {
		check(uri);
		Intent intent = new Intent(this, to);
		intent.setData(Uri.parse(uri));
		intent.putExtras(extras);
		startActivity(intent);
	}

	/**
	 * 启动其它单例activity。
	 * 
	 * @param to
	 *            要启动的单例activity对应的class。
	 * 
	 * @throws InvalidParameterException
	 */
	public void go(Class<?> to, Bundle extras) {
		Intent intent = new Intent(this, to);
		intent.putExtras(extras);
		startActivity(intent);
	}

	/**
	 * 启动其它单例activity。
	 * 
	 * @param to
	 *            要启动的单例activity对应的class。
	 * @param name
	 *            参数name
	 * @param value
	 *            参数value
	 * 
	 * @throws InvalidParameterException
	 */
	public final void go(Class<?> to, String name, int value) {
		Intent intent = new Intent(this, to);
		intent.putExtra(name, value);
		startActivity(intent);
	}

	public final void go(Class<?> to, String name, long value) {
		Intent intent = new Intent(this, to);
		intent.putExtra(name, value);
		startActivity(intent);
	}

	/**
	 * 启动其它单例activity。
	 * 
	 * @param to
	 *            要启动的单例activity对应的class。
	 * @param intent
	 *            要处理的INTENT
	 * 
	 * @throws InvalidParameterException
	 */
	public final void go(Intent intent) {
		startActivity(intent);
	}

	protected final void check(String url) {
		if (url == null || !url.contains("://")) {
			throw new InvalidParameterException("Pls use ABSOLUTE path for URL");
		}
	}

	/**
	 * 延时启动其它单例activity，并结束原来的activity。
	 * 
	 * @param to
	 *            要启动的单例activity对应的class。
	 * @param delay
	 *            延迟的毫秒数。
	 */
	public final void goAndFinish(final Class<?> to, long delay) {
		// new Timer().schedule(new TimerTask() {
		// @Override
		// public void run() {
		// TODO Auto-generated method stub
		BaseScreen.this.startActivity(new Intent(BaseScreen.this, to));
		BaseScreen.this.finish();
		// }
		// }, delay);
	}

	/**
	 * 显示 键盘
	 * 
	 */
	public void showKeyBorad(EditText editbox) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editbox, InputMethodManager.SHOW_FORCED);
	}

	Toast mToast;

	public void ShowToast(final String text) {
		if (!TextUtils.isEmpty(text)) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (mToast == null) {
						mToast = Toast.makeText(getApplicationContext(), text,
								Toast.LENGTH_LONG);
					} else {
						mToast.setText(text);
					}
					mToast.show();
				}
			});

		}
	}

	public void ShowToast(final int resId) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (mToast == null) {
					mToast = Toast.makeText(getApplicationContext(), resId,
							Toast.LENGTH_LONG);
				} else {
					mToast.setText(resId);
				}
				mToast.show();
			}
		});
	}

	/**
	 * 隐藏软键盘 hideSoftInputView
	 * 
	 * @Title: hideSoftInputView
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 */
	public void hideSoftInputView() {
		InputMethodManager manager = ((InputMethodManager) this
				.getSystemService(Activity.INPUT_METHOD_SERVICE));
		if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	/**
	 * 隐藏 键盘
	 * 
	 */
	public void hideKeyBorad(EditText editbox) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editbox.getWindowToken(), 0);
	}

	private void intitAction() {
		action = new Hashtable<String, Class<?>>();
		// 进圈子
		// "http://tool.test.com/group/1",
		action.put("http://tool.test.com/group", CircleTopicActivity.class);
		// 进帖子
		// "http://tool.test.com/subject/1/2",
		action.put("http://tool.test.com/subject", TopicAndResultActivity.class);
		// 问医生
		// "http://tool.test.com/docask/1",
		action.put("http://tool.test.com/docask", AskDoctorActivity.class);
		// 医生专题
		// "http://tool.test.com/docspec/1/asfafa%32%32%32%32adsfas",
		action.put("http://tool.test.com/docspec", DoctorOnlineActivity.class);
		// 普通专题
		// "http://tool.test.com/hotspec/1/asfadsfasdfasf",
		action.put("http://tool.test.com/docspec", DoctorOnlineActivity.class);
	}

	/**
	 * 根据action 跳转到到不同的页面，主要是展位在使用
	 * 
	 * @param paction
	 * @param pbean
	 */
	public void goAction(String paction) {
		if (paction == null) {
			return;
		}

		if (TextUtils.isEmpty(paction))
			return;
		if (paction.startsWith("http:")) {
			Intent intent = new Intent(mContext, AdverltWebView.class);
			intent.putExtra(KidAction.INTENT_URL, paction + "");
			startActivity(intent);
		} else {
			String[] end = paction.split("\\//")[1].split("\\/");
			Intent intent = null;
			if (paction.contains("subject")) {// 进帖子详情
				intent = new Intent(mContext, TopicAndResultActivity.class);
				intent.putExtra(TopicAndResultActivity.STR_TOPIC_ID, end[2]);
				intent.putExtra(TopicAndResultActivity.STR_GROUP_ID, end[1]);
			} else if (paction.contains("group")) {// 进圈子
				intent = new Intent(mContext, CircleTopicActivity.class);
				intent.putExtra(TopicAndResultActivity.STR_GROUP_ID, end[1]);
			} else if (paction.contains("docask")) {// 医生
				intent = new Intent(mContext, ToAskDoctorActivity.class);
				intent.putExtra("campaign_id", end[1]);
			} else if (paction.contains("docspec")) {// 医生专题
				intent = new Intent(mContext, TopicsSheetListActivity.class);
				intent.putExtra("catalog_id", end[1]);
			} else if (paction.contains("hotspec")) {// 普通专题
				intent = new Intent(mContext, TopicsSheetListActivity.class);
				intent.putExtra("catalog_id", end[1]);
			} else if (paction.contains("docintro")) {// 医生简介
				intent = new Intent(mContext, DoctorInfoActivity.class);
				intent.putExtra("doctor_id", end[1]);
			} else if (paction.contains("docol")) {// 医生在线
				dialog = new DialogImpl();
				progress = (ProgressDialog) dialog.showProgressDialog(this,
						"请稍等...", new onChannelListener(this));
				ActiveStateUtil.getInstance(this)
						.gogoActionsDoctorOnlineByStatus(end[2], progress);
			}
			if (intent == null)
				return;
			startActivity(intent);
		}
	}

	public static boolean isConnect(Context context) {
		// 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
		try {
			ConnectivityManager connectivity = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				// 获取网络连接管理的对象
				NetworkInfo info = connectivity.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					// if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
					// }
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			QLog.debug("error", e.toString());
		}
		return false;
	}

	public boolean islogon() {
		if (mApplication.mMyUser.iAnonymousToken()) {
			Intent t = new Intent(mContext, RegAndLoginActivity.class);
			t.putExtra(KidAction.FROM, "");
			t.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(t);
			return false;
		} else {
			return true;
		}

	}

	/**
	 * 计算预产期与当前时间相差天数
	 * 
	 * @param date
	 * @return
	 */
	public int compairTime(String[] date) {
		String date1 = date[0] + "-" + date[1] + "-" + date[2];
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date d = df.parse(date1);
			long milliSecondSub = d.getTime() - System.currentTimeMillis();
			long day = milliSecondSub / 1000 / 60 / 60 / 24;
			QLog.debug("error",
					"---------------" + String.valueOf(milliSecondSub));
			QLog.debug("error", "---------------" + String.valueOf(day));

			return (int) day;

		} catch (java.text.ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 1000;// 执行到这里说明抛ParseException
	}
	
	/**
	 * 如果指定日期小于当前日期返回true
	 * @param t1  指定日期
	 * @return
	 */
	public boolean isBeforeToday(String[] myTime){
		String t1=myTime[0]+","+myTime[1]+","+myTime[2];
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy,MM,dd");
		String dateString = formatter.format(currentTime);
        Calendar c1=Calendar.getInstance();
        Calendar c2=Calendar.getInstance();
        try {
            c1.setTime(formatter.parse(t1)); //当前
            c2.setTime(formatter.parse(dateString));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int result=c1.compareTo(c2);
        if(result==-1){
        	 return true;
        }else{
        	return false;
        }
	}

	/**
	 * 当前日期与指定日期相差天数（如：当前2015,07,03 指定日期2015,07,01 返回2）
	 * （局限性：只能计算同一年中的两个日期相差的天数）
	 * @param fDate
	 *            指定的日期
	 * @return
	 */
	public int daysOfTwo(String[] date/* , Date oDate */) {
		String date1 = date[0] + "-" + date[1] + "-" + date[2];
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		
		Calendar aCalendar = Calendar.getInstance();
		try {
			aCalendar.setTime(df.parse(date1));//指定时间
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
		aCalendar.setTime(new Date()); // 当前时间
		int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
		return day2 - day1;

	}

	/**
	 * 当前日期与指定日期相差年数（如：当前2015 指定2018 返回-3）
	 * 
	 * @param fDate
	 *            指定的日期
	 * @return
	 */
	public int yearsOfTwo(String[] date) {
		String date1 = date[0] + "-" + date[1] + "-" + date[2];
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar aCalendar = Calendar.getInstance();
		try {
			aCalendar.setTime(df.parse(date1)); //指定时间
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		int day1 = aCalendar.get(Calendar.YEAR);
		aCalendar.setTime(new Date()); // 当前时间
		int day2 = aCalendar.get(Calendar.YEAR);// DAY_OF_YEAR
		return day2 - day1;
	}

}